<template>
	<view>
		<!-- navbar -->
		<van-nav-bar @click-left="$back" left-arrow title="选择红包/抵用券" :border="false" />
		<scroll-view scroll-y :style="{height: height, backgroundColor: '#f8f8f8'}">
			<van-radio-group :border="false" :value="coupon" @change="onChange">
				<van-cell-group :border="false">
					<van-cell title-width="160rpx" center size="large" clickable :data-name="item.id"
						@click="onClick" v-for="(item, index) in couponList" :key="index">
						<view slot="title" class="cell-left">
							<text style="color: #EE0A24;font-size: 36rpx;font-weight: bold;">&yen;{{item.reduction}}</text>
							<text style="color: #999999;font-size: 24rpx;">{{item.fullUp == 0 ? '任意立减' : `满${item.fullUp}可用`}}</text>
						</view>
						<view class="cell-right">
							<text style="color: #000000;font-size: 28rpx;font-weight: bold;">{{item.title}}</text>
							<text style="color: #999;font-size: 24rpx;">{{item.endTime}}到期</text>
						</view>
						<van-radio style="position: relative;top: 4rpx;" checked-color="#ee0a24" slot="right-icon"
							:name="item.id" />
					</van-cell>
				</van-cell-group>
			</van-radio-group>
			<van-empty description="无优惠券可用~" v-if="couponList.length===0"/>
		</scroll-view>
		<van-submit-bar label="可减" :price="(coupon == -1 ? 0 : (curItem.reduction || 0)) * 100" button-text="确定" @submit="onSubmit" />
	</view>
</template>

<script>
	import {mapState} from 'vuex';
	export default {
		data() {
			return {
				coupon: -1, // 优惠券id
				curItem: {} // 当前选中
			}
		},
		computed: {
			...mapState(['couponList']),
			height() {
				return this.scrollviewHeilght - 96 + 'px'
			}
		},
		onLoad({status, coupon, price}) {
			// 已选择过, 进来重选
			if(status == 2) {
				let item = this.couponList.find(item => item.id == coupon);
				this.curItem = item;
				this.coupon = item.id;
			} else {
			// 第一次进来	
				let maxItem = this.couponList[0];
				this.couponList.forEach(item => {
					if(item.reduction > maxItem.reduction) {
						maxItem = item;
					}
				})
				this.curItem = maxItem;
				this.coupon = maxItem.id;
			}
		},
		methods: {
			onSubmit() {
				// 未选中红包
				let item = {
					reduction: this.curItem.reduction,
				};
				if(this.coupon === -1) {
					item.id = -1;
				} else {
				// 已选中红包	
					item.id = this.curItem.id;
				}
				uni.$emit('handleCoupon', item);
				this.$back();
			},
			onChange({
				detail
			}) {
				this.coupon = detail;
			},
			onClick(event) {
				const {
					name
				} = event.currentTarget.dataset;
				let curItem = this.couponList.find(item => item.id == name);
				if(this.coupon === name) {
					this.coupon = -1;
				} else {
					this.coupon = name;
				}
				this.curItem = curItem;
			},
		}
	}
</script>

<style lang="scss" scoped>
	.cell-left {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.cell-right {
		display: flex;
		flex-direction: column;
		text-align: left;
		padding-left: 32rpx;
	}
</style>
